<template>
  <el-dialog title="添加卡片-产品"  :close-on-click-modal="false" :visible.sync="show" 
  class="dialog_index dialog_banner" id="addProduct" :before-close="cancle" >
   <el-form ref="bannerForm" class="scroll" v-loading="loading">
      <el-tabs type="card"  v-model="activeTab">
        <el-tab-pane :label="item.site" :name="item.site"  v-for="(item, index)  in formList" :key="item.id">
            <el-upload class="upload-banner" action="/api/api/general/upload"   
            :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, item)"
             :on-error="handleBannerError" :before-upload="beforeBannerUpload"
            :show-file-list="false" accept=".png " :data="{type:'banner_product',imageheight: imgH, imagewidth: imgW}" >
              <el-button size="small" type="primary" @click.stop="chooseGallery(index)">图库选择</el-button>
              <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              <div class="pop_container">
                <img v-if="item.image" :src="utils.setCdnUrl() + item.image" class="pop_image">
              </div>
            </el-upload>
            <p class="banner_title">卡片设置</p>
            <el-form-item label="卡片形式：">
              <el-radio-group v-model="item.banner_product_type" @change="value => changeBannerType(value,item)">
                <el-radio label="1">一图多站点</el-radio>
                <el-radio label="2">多图多站点</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="一级标题：">
              <el-input  :placeholder="'一级标题('+item.site+')（非必填项)'" v-model="item.first_title"></el-input>
            </el-form-item>
            <el-form-item label="二级标题：">
              <el-input :placeholder="'二级标题('+item.site+')（非必填项)'" v-model="item.second_title"></el-input>
            </el-form-item>
            <p class="banner_title">关联产品</p>
            <el-form-item label="关联类型：">
              <el-select v-model="item.relation_type" placeholder="关联类型（必填项）" @change="value => chnageRelationType(value, item)">
                <el-option v-for="item in associationTypeList" :key="item.value"  :label="item.label"  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联产品：" >
              <el-select v-model="item.product_id"  placeholder="关联产品（非必填项）"   @focus="(event) => getProductSelectList(event, item)"  @change="value => changeProduct(value,item)">
                <el-option v-for="item in item.relationProductList" :key="item.value"  :label="item.label"  :value="item.product_id"></el-option>
              </el-select>
            </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'banner_product'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

   </el-dialog>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { siteListGet } from '@/api/manage/site.js'
import { extendObj, setErrorTip } from '@/utils/index'
import { bannerProductAdd } from '@/api/index/bannerProduct.js'
import { productSelectList } from '@/api/product/productBasic.js'

export default {
  data () {
    return {
      formList: [],
      loading: false,
      imgH: '',
      imgW: '',
      associationTypeList: [
        {value:'2', label: '统一关联'},
        {value:'3', label: '分别关联'},
      ],
      activeTab: '',
      showDrawer: false,
      cur_index: 0, //选择的站点
    }
  },
  components: { Drawer },
  props: {
    show: Boolean,
    closeDialog:Function,
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getSite()
      }
    }
  },
  methods: {
    // 若卡片形式为“一图多站点”时，每个站点自动填充产品图；
    // 若卡片形式为“多图多站点”时，在当前站点上传的产品图只会在当前站点有；
    changeBannerType (value, item) {
      let bannerList = this.formList
      if(value == 1){
        // 一个个BANNER多个站点
        for(let i = 0; i < bannerList.length; i++){
          bannerList[i].image = item.image
          bannerList[i].httpImage = item.httpImage
        }
      } 
      for(let i = 0; i < bannerList.length; i++){
        bannerList[i].banner_product_type = item.banner_product_type
      }
      this.formList = bannerList
    },
    chooseGallery (index) {
      this.showDrawer = true
      this.cur_index = index
    },
       // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathName) { 
        let cur_item = this.formList[this.cur_index]
        cur_item.image = data.filePathName
        cur_item.httpImage = data.filePathNameHttp
        this.changeBannerType(cur_item.banner_product_type, cur_item)
      }
    },
    getProductSelectList (event,item) {
      if (event && item.relation_type == ''){
        item.relationProductList = []
        this.$message.error('优先选择关联类型')
        return
      }else {
        let params = {
          site_id: item.site_id
        }
        productSelectList(params).then(res=>{
          item.relationProductList = res.data
        })
      }
     
    },
    chnageRelationType (val, item) {
      let bannerList = this.formList
      if (val == 2 ){
        // 统一关联
        for(let i = 0; i < bannerList.length; i++){
          bannerList[i].relation_type = item.relation_type
          bannerList[i].product_id = item.product_id
        }
      }else{
        for(let i = 0; i < bannerList.length; i++){
          bannerList[i].relation_type = item.relation_type
        }
      }
    },

    changeProduct (value, item) {
      let list = this.formList
      if (item.relation_type == 2){
        for(let i = 0 ; i < list.length; i++){
          list[i].product_id = value
        }
      }
    },
    handleBannerSuccess (response, res, fileList, item) {
      if(response.state != 1){
        this.$message.error('上传图片失败:' + setErrorTip(response) )   
      }
      item.image = response.data.filePathName
      item.httpImage = response.data.filePathNameHttp
      if(item.banner_product_type == 1){
        this.changeBannerType(1, item)
      }
    },
    
    handleBannerError(){
      this.$message.error('上传图片失败')   
    },
    beforeBannerUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/png'){
        this.$message.error("仅支持.png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          // let valid = img.width == img.height ;
          let valid = true
          that.imgW = img.width
          that.imgH = img.height
          valid ? resolve() : reject();
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        that.$message.error('上传图片尺寸为1:1')
        return Promise.reject()
      })
      return isSize
    },
  
    getSite (){
      siteListGet().then(res=>{
        if (res.status == 200) {
          let data = res.data
          for(let i = 0; i < data.length; i++){
            let obj = {
              image: '',
              first_title: '',
              second_title	: '',
              site_id: data[i].id,
              association_types: '0',
              association_types_name: '',
              association_types_id: null,
              httpImage:'',
              relation_type: '',
              product_id: null,
              relationProductList: [],
              banner_product_type: '1'
            }
            extendObj(data[i], obj)
            this.getProductSelectList(null, data[i])
            if (i == 0){
              this.activeTab = data[i].site
            }
          }
          this.formList= data
          this.loading = false
        }

      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status){
        this.addBannerProduct()
      }
      
    },
    validateForm () {
      let list = this.formList
      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].image === '') {
          this.$message.error('站点' + list[i].site + '图片为必填项')
          status = false
          break
        }

        if (list[i].first_title.length > 100) {
          this.$message.error('站点' + list[i].site + '一级标题最多100字符')
          status = false
          break
        }
        if (list[i].second_title.length > 200) {
          this.$message.error('站点' + list[i].site + '二级标题最多200字符')
          status = false
          break
        }
        if (list[i].relation_type === '') {
          this.$message.error('站点' + list[i].site + '关联类型为必填项')
          status = false
          break
        }

      }
      return status
    },
    
    addBannerProduct () {
      let list = this.formList
      console.log(list)
      for(let i = 0; i < list.length; i++ ){
        let productList = list[i].relationProductList 
        for(let j = 0; j < productList.length; j++){
          if(list[i].product_id == productList[j].product_id){
            list[i].association_types_id = productList[j].id
            list[i].association_types_name = productList[j].label
          }
        }
      }
      let params = {
        data: JSON.stringify(list) 
      }
      bannerProductAdd(params).then(res => {
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
      })
    },

    cancle(){
      // this.$refs.addSiteFrom.clearValidate();
      this.$refs.bannerForm.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')

    },
  },
 
}
</script>

<style>

</style>